package mercadologico.entities.tables;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

import mercadologico.dao.PersistenceMedida;

import exceptions.PersistenceExceptionMessage;
import generic.interfaces.GenericPersistence;
import generic.interfaces.IDEntity;
import generic.interfaces.PersistInFile;

@SuppressWarnings("rawtypes")
@Entity
public class Medida implements IDEntity<String>, GenericPersistence<PersistenceMedida, String, Medida>, PersistInFile, Comparable<Medida> {

	public static PersistenceMedida persist = new PersistenceMedida();
	
	@Id
	@Column(length=2)
	private String id;
	private String descricao;
	private Double valorUnitario;
	
	
	public String getId() {
		return this.id;
	}
	
	public void setId(String id) {
		this.id = id;
	}
	public String getDescricao() {
		return descricao;
	}
	public void setDescricao(String descricao) {
		this.descricao = descricao;
	}
	public Double getValorUnitario() {
		return valorUnitario;
	}
	public void setValorUnitario(Double valorUnitario) {
		this.valorUnitario = valorUnitario;
	}
	
	public PersistenceMedida DAOInstance() {
		if (persist == null) {
			persist = new PersistenceMedida();
		}
		return persist;
	}

	
	public Medida find(String id) throws PersistenceExceptionMessage {
		return DAOInstance().find(id);
	}

	
	public void persist() throws PersistenceExceptionMessage {
		DAOInstance().persist(this);
	}

	
	public void remove() throws PersistenceExceptionMessage {
		DAOInstance().remove(this);
	}

	
	public Medida merge() throws PersistenceExceptionMessage {
		return DAOInstance().merge(this);
	}

	
	public ArrayList<Medida> findAll() throws PersistenceExceptionMessage {
		return (ArrayList<Medida>) DAOInstance().findAll();
	}
	
	public String toString() {
		return getId();
	}
	
	public Object getInstanceFromArray(String[] str) {
		for (String string : str) {
			if (string == null)
				return null;
			if (string.trim().length() == 0)
				return null;
		}

		if (str != null && str.length == 3) {
			Medida medida = new Medida();
			medida.setId(str[0]);
			medida.setDescricao(str[1]);
			medida.setValorUnitario(Double.parseDouble(str[2]));
			return medida;
		}
		return null;
	}
	@SuppressWarnings({ "unchecked"})
	
	public Collection<Medida>  order(ArrayList entities) {
		Collections.sort(entities);
		return entities;
	}
	
	public int removeAll() throws PersistenceExceptionMessage {
		return DAOInstance().removeAll();
	}
	
	public int compareTo(Medida arg0) {
		return getDescricao().compareToIgnoreCase(arg0.getDescricao());
	}
	
	public ArrayList<String> getArrayAsString() throws PersistenceExceptionMessage {
		ArrayList<String> strs = new ArrayList<String>();
		for (Medida me : order((ArrayList) DAOInstance().findAll())) {
			strs.add(me.getId() +"|" +me.getDescricao() +"|" +me.getValorUnitario());
		}
		return strs;
	}
}
